package org.sninwo.lnbook.book.web.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sninwo.lnbook.book.entity.User;
import org.sninwo.lnbook.book.service.UserManager;
import org.sninwo.lnbook.uitls.LangUtils;

public class ShiroRealm extends AuthorizingRealm {
	static Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

	@Resource private UserManager userMgr;
	
	public ShiroRealm(){
		setName("ShiroRealm");
	}
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		logger.debug("验证用户登陆");
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String userName = token.getUsername();
		User user = userMgr.getUserByName(userName);
		if (user == null) return null;
		//用md5串对比密码
		String md5Pwd = LangUtils.md5(new String(token.getPassword()));
		token.setPassword(md5Pwd.toCharArray());
		return new SimpleAuthenticationInfo(userName, user.getPassword(), getName());
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}
	
	public void onLogout(PrincipalCollection principals){
		logger.debug("用户{}退出登陆", principals.iterator().next().toString());
		super.onLogout(principals);
	}
}
